package com.kevis.zhunblog.admin.security.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.kevis.zhunblog.admin.security.entity.SecurityUser;
import com.kevis.zhunblog.core.entities.AdminEntity;
import com.kevis.zhunblog.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

@Component("userDetailsService") //这边我觉得还是写一下好。只有一个的时候也可以使用。但是有多个的时候可能会找不到。
public class UserLoginService implements UserDetailsService {

    @Autowired
    private AdminService adminService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //去数据库查询这个用户是否存在
        AdminEntity adminEntity = adminService.getOne(new LambdaQueryWrapper<AdminEntity>().eq(AdminEntity::getAdminName, username));
        if (null == adminEntity || adminEntity.getStatus() == -1) {
            throw new UsernameNotFoundException("用户不存在");
        }
        //获取对应的角色权限
        List<GrantedAuthority> auths =
                AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_" + adminEntity.getRoleId().toString());
//        SecurityUser securityUser = new SecurityUser(username, adminEntity.getAdminPassword(),auths);
//        securityUser.setRoleId(manageAdmin.getF_RoleID());
//        return new User(username, adminEntity.getAdminPassword(), auths);
        SecurityUser securityUser = new SecurityUser(username, adminEntity.getAdminPassword(),adminEntity.getRoleId(), auths);
        securityUser.setUserId(adminEntity.getId());
        securityUser.setRoleId(adminEntity.getRoleId());
        return securityUser;
    }
}
